﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using intelliPaper.Model;
using System.Linq;
using intelliSys.Management.Automation.Profiler.Properties;
using System.Windows.Media.Animation;
using System.Xml.Serialization;
using System.Reflection;
using System.Collections;
using intelliSys.UI.Interaction.MouseGesture;

namespace intelliSys.Management.Automation.Profiler
{
    /// <summary>
    /// Interaction logic for Result.xaml
    /// </summary>
    public partial class Result : Window
    {
        Stack<System.Collections.IEnumerable> Contexts = new Stack<System.Collections.IEnumerable>();
        public Result()
        {
            this.InitializeComponent();
            this.Height = SystemParameters.WorkArea.Height;
            this.Width = SystemParameters.WorkArea.Width;
            this.Loaded += new RoutedEventHandler(Result_Loaded);
            tabControl.Loaded += new RoutedEventHandler(tabControl_Loaded);
            tabControl.SelectionChanged += new SelectionChangedEventHandler(tabControl_SelectionChanged);
            WidthHeightCollection[7].Width = this.Width;
            WidthHeightCollection[7].Height = this.Height;
            ResolutionIdx = 7;
            AdjustTransparancy();
            if (!Settings.Default.UseSQL)
            {
                dangerZone.Visibility = System.Windows.Visibility.Collapsed;
            }
            // Insert code required on object creation below this point.
        }

        void AdjustTransparancy()
        {
            if (Settings.Default.AllowTransparancy == false)
            {
                transparancyCompensator.Visibility = System.Windows.Visibility.Hidden;
                this.AllowsTransparency = false;
                this.Background = new SolidColorBrush(Colors.White);
            }
            else
            {
                transparancyCompensator.Visibility = System.Windows.Visibility.Visible;
                this.AllowsTransparency = true;
                this.Background = new SolidColorBrush(Colors.Transparent);
            }
        }
        bool Working = false;
        void AdjustPerformance(int lvl)
        {
            this.lvl = lvl;
            slider_DragDelta(null, new System.Windows.Controls.Primitives.DragDeltaEventArgs(0, 0));
        }
        void tabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (tabControl.SelectedItem == performanceTabItem)
            {
                if (!Working && Settings.Default.AutoDecide)
                {
                    SystemInfoNA.Text = "retrieving...";
                    GenerateWINSATSummary();
                }
            }
        }

        private void GenerateWINSATSummary()
        {
            performanceRetrievingIndicator.Visibility = System.Windows.Visibility.Visible;
            experienceIndexRoot.Visibility = System.Windows.Visibility.Collapsed;
            System.Threading.ThreadPool.QueueUserWorkItem(o =>
            {
                Working = true;
                bool success = true;
                intelliSys.Environment.Performance.WinSAT.WinSATSummary summary = null;
                System.Threading.Thread.Sleep(5000);
                try
                {
                    summary = intelliSys.Environment.Performance.WinSAT.WinSATSummary.GetSummary();
                }
                catch (ApplicationException)
                {
                    success = false;
                }
                this.Dispatcher.Invoke(new Action(() =>
                {
                    if (success)
                    {
                        if (summary.CPU == "0")
                        {
                            SystemInfoNA.Text = "you may need to refresh yor WINSAT score";
                        }
                        else
                        {
                            SystemInfoNA.Text = "retrieved from WINSAT just now";
                        }
                        experienceIndexRoot.Visibility = System.Windows.Visibility.Visible;
                        CPUMark.Text = summary.CPU;
                        GraphicsMark.Text = summary.Graphics;
                        GamingGraphicsMark.Text = summary.DirectX3D;
                        DiskMark.Text = summary.Disk;
                        RAMMark.Text = summary.Memory;
                        RedrawShadow();
                        if (SystemMark.Text.CompareTo("5.9") >= 0)
                        {
                            AdjustPerformance(2);
                        }
                        else if (SystemMark.Text.CompareTo("4.9") >= 0)
                        {
                            AdjustPerformance(1);
                        }
                        else
                        {
                            AdjustPerformance(0);
                        }
                    }
                    else
                    {
                        SystemInfoNA.Text = "performance information not available, defaulted to 0";
                        AdjustPerformance(0);
                    }
                    performanceRetrievingIndicator.Visibility = System.Windows.Visibility.Collapsed;
                }));
            });
        }

        void RedrawShadow()
        {
            CPUMark.Background = RAMMark.Background = GraphicsMark.Background = GamingGraphicsMark.Background = DiskMark.Background = new SolidColorBrush(Colors.White);
            var array = new[] { CPUMark, RAMMark, GraphicsMark, GamingGraphicsMark, DiskMark };
            var list = new List<TextBlock>();
            double lowest = 8;
            foreach (var item in array)
            {
                if (double.Parse(item.Text) < lowest)
                {
                    lowest = double.Parse(item.Text);
                }
            }
            foreach (var item in array)
            {
                if (item.Text == lowest.ToString())
                {
                    item.Background = grid5.Background;
                }
            }
            SystemMark.Text = lowest.ToString();
        }

        void Default_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
        {
            Apply.Visibility = System.Windows.Visibility.Visible;
            Cancel.Visibility = System.Windows.Visibility.Visible;
        }

        void Result_Loaded(object sender, RoutedEventArgs e)
        {
            if (Settings.Default.GraphicsLevel == 2)
            {
                expand = this.Resources["expandDetail"] as Storyboard;
                shrink = this.Resources["collapseDetail"] as Storyboard;
                fadeIn = this.Resources["TransitIn"] as Storyboard;
                fadeOut = this.Resources["TransitOut"] as Storyboard;
                showSearch = this.Resources["ShowSearch"] as Storyboard;
                drawNearIn = this.Resources["drawNearIn"] as Storyboard;
                drawFarIn = this.Resources["drawFarIn"] as Storyboard;
                drawNearOut = this.Resources["drawNearOut"] as Storyboard;
                drawFarOut = this.Resources["drawFarOut"] as Storyboard;
                refreshListShow = this.Resources["refreshListShow"] as Storyboard;
                refreshListFade = this.Resources["refreshListFade"] as Storyboard;
                fastFadeLeft = this.Resources["fastFadeLeft"] as Storyboard;
                flashStackPanel = this.Resources["flashstackpanel"] as Storyboard;
                turnRed = this.Resources["turnRed"] as Storyboard;
                turnWhite = this.Resources["turnWhite"] as Storyboard;
                drawFarOut.Completed += new EventHandler(drawFarOut_Completed);
                drawNearOut.Completed += new EventHandler(drawNearOut_Completed);
                showSearch.Completed += new EventHandler(showSearch_Completed);
                refreshListFade.Completed += new EventHandler(refreshList_Completed);
            }
            else if (Settings.Default.GraphicsLevel == 1)
            {
                expand = this.Resources["expandDetail"] as Storyboard;
                shrink = this.Resources["collapseDetail"] as Storyboard;
                fadeIn = this.Resources["TransitIn"] as Storyboard;
                fadeOut = this.Resources["TransitOut"] as Storyboard;
                showSearch = this.Resources["ShowSearch"] as Storyboard;
                drawNearIn = this.Resources["drawNearIn"] as Storyboard;
                drawFarIn = this.Resources["drawFarIn"] as Storyboard;
                drawNearOut = this.Resources["drawNearOut"] as Storyboard;
                drawFarOut = this.Resources["drawFarOut"] as Storyboard;
                refreshListShow = this.Resources["dummy2"] as Storyboard;
                refreshListFade = this.Resources["dummy2"] as Storyboard;
                fastFadeLeft = this.Resources["dummy1"] as Storyboard;
                flashStackPanel = this.Resources["dummy1"] as Storyboard;
                turnRed = turnWhite = Resources["dummy5"] as Storyboard;
                drawFarOut.Completed += new EventHandler(drawFarOut_Completed);
                drawNearOut.Completed += new EventHandler(drawNearOut_Completed);
                showSearch.Completed += new EventHandler(showSearch_Completed);
                refreshListFade.Completed += new EventHandler(refreshList_Completed);
            }
            else
            {
                expand = this.Resources["expandDetail"] as Storyboard;
                shrink = this.Resources["collapseDetail"] as Storyboard;
                fadeIn = this.Resources["dummy5"] as Storyboard;
                fadeOut = this.Resources["dummy5"] as Storyboard;
                showSearch = this.Resources["dummy1"] as Storyboard;
                drawNearIn = this.Resources["dummy5"] as Storyboard;
                drawFarIn = this.Resources["dummy5"] as Storyboard;
                drawNearOut = this.Resources["dummy2"] as Storyboard;
                drawFarOut = this.Resources["dummy3"] as Storyboard;
                refreshListShow = this.Resources["dummy5"] as Storyboard;
                refreshListFade = this.Resources["dummy4"] as Storyboard;
                fastFadeLeft = this.Resources["dummy5"] as Storyboard;
                flashStackPanel = this.Resources["dummy5"] as Storyboard;
                drawFarOut.Completed += new EventHandler(drawFarOut_Completed);
                drawNearOut.Completed += new EventHandler(drawNearOut_Completed);
                showSearch.Completed += new EventHandler(showSearch_Completed);
                refreshListFade.Completed += new EventHandler(refreshList_Completed);
                turnWhite = turnRed = Resources["dummy5"] as Storyboard;
            }
            if (Settings.Default.MouseGestureGeneral)
            {
                if (Settings.Default.AllowShake)
                {
                    Shake shk = new Shake(this);
                    shk.RequiredIntensity = 100;
                    shk.ExpectedRecursionCount = 3;
                    shk.InstantFire = true;
                    shk.OnSensed += new EventHandler<MouseGestureEventArgBase>(shk_OnSensed);
                }
                if (Settings.Default.AllowHold)
                {
                    Hold hld = new Hold(this);
                    hld.InstantFire = true;
                    hld.OnSensed += new EventHandler<MouseGestureEventArgBase>(hld_OnSensed);
                }
                if (Settings.Default.AllowGlide)
                {
                    //Application.Current.ShutdownMode = ShutdownMode.OnExplicitShutdown;
                    Glide gld = new Glide(this);
                    gld.InstantFire = true;
                    gld.SensitivityInterval = 50;
                    gld.Intensity = 50;
                    gld.Speed = 15000;
                    gld.Distance = (int)SystemParameters.WorkArea.Height;
                    gld.OnSensed += new EventHandler<MouseGestureEventArgBase>(gld_OnSensed);
                }
            }
            this.MouseLeftButtonDown += new MouseButtonEventHandler(Result_MouseLeftButtonDown);
            this.MouseLeftButtonUp += new MouseButtonEventHandler(Result_MouseLeftButtonUp);
            toggleShowAll.IsEnabled = false;
            IEnumerable<ISearchable> tier1 = DataRepository.Questions;
            EquivalantTier = 3;
            if (DataRepository.KnowledgePoints.Count != 0)
            {
                tier1 = DataRepository.KnowledgePoints;
                EquivalantTier = 2;
            }
            if (DataRepository.Papers.Count != 0)
            {
                tier1 = DataRepository.Papers;
                EquivalantTier = 1;
            }
            //Contexts.Push(tier1);
            if (tier1.Count() == 0)
            {
                lonely_in_here.Visibility = System.Windows.Visibility.Visible;
                searchCpanel.Visibility = System.Windows.Visibility.Collapsed;
            }
            listBox.ItemsSource = now = tier1;
            summaryBox.ItemsSource = SystemStatistics.GetStatisticsCollection();
        }

        void RefreshSettingPanel()
        {
            Fine.Fill = colors[Settings.Default.Fine];
            Moderate.Fill = colors[Settings.Default.Moderate];
            Severe.Fill = colors[Settings.Default.Severe];
            highlightGauge.Background = new SolidColorBrush(Colors.White);
            highlightGauge.Foreground = new SolidColorBrush(Colors.Black);
            lvl = Settings.Default.GraphicsLevel;
            slider.RenderTransform = new TranslateTransform(lvl * 100, 0);
            pastRect.Width = lvl * 100;
            effectSummary.Text = GraphicsSummary[lvl];
            tabControl.DataContext = Settings.Default;
        }
        void tabControl_Loaded(object sender, RoutedEventArgs e)
        {
            RefreshSettingPanel();
            Settings.Default.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(Default_PropertyChanged);

        }

        void Result_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            this.Height = WidthHeightCollection[ResolutionIdx].Height;
            this.Width = WidthHeightCollection[ResolutionIdx].Width;
            // AdjustTransparancy();
        }

        void gld_OnSensed(object sender, MouseGestureEventArgBase e)
        {
            foreach (Window wnd in Application.Current.Windows)
            {
                wnd.Close();
            }
        }

        void hld_OnSensed(object sender, MouseGestureEventArgBase e)
        {
            MessageBox.Show("This version of application is not loaded with a Help System.");
        }
        class WidthAndHeight
        {
            public double Width;
            public double Height;
        }
        static int ResolutionIdx;
        static WidthAndHeight[] WidthHeightCollection =
        { 
            new WidthAndHeight()
            {
                Width=800,
                Height=600
            } ,
            new WidthAndHeight()
            {
                Width=960,
                Height=600
            },
            new WidthAndHeight()
            {
                Width = 1024,
                Height=768
            },
            new WidthAndHeight()
            {
                Width=1280,
                Height=720
            },
            new WidthAndHeight()
            {
               Width=1280,
                Height=768
            },
             new WidthAndHeight()
            {
               Width=1366,
                Height=760
            },
            new WidthAndHeight()
            {
               Width=1366,
                Height=768
            },
            new WidthAndHeight()
        };
        void shk_OnSensed(object sender, MouseGestureEventArgBase e)
        {
            ResolutionIdx = (ResolutionIdx + 1) % 7;
        }




        void Result_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            this.DragMove();
        }
        int equivalantTier;
        int EquivalantTier
        {
            get
            {
                return equivalantTier;
            }
            set
            {
                if (value < 1 || value > 3)
                {
                    throw new ApplicationException("BUGCHECK");
                }
                equivalantTier = value;
            }
        }
        void drawNearOut_Completed(object sender, EventArgs e)
        {
            //MessageBox.Show("executed");
            IEnumerable<ISearchable> source = null;
            if (EquivalantTier == 1)
            {
                var selected = clicked.DataContext as Paper;
                source = selected.KnowledgePoints;
            }
            if (EquivalantTier == 2)
            {
                var selected = clicked.DataContext as KnowledgePoint;
                source = DataRepository.Questions.Where<Question>(o =>
                {
                    return o.KnowledgePoints.Contains(selected);
                });
            }
            listBox.ItemsSource = source;
            drawNearIn.Begin();
            InvalidateTextQ();
            throttleSpeed.Visibility = Visibility.Visible;
            toggleShowAll.IsEnabled = true;
            //progressbar.Visibility = System.Windows.Visibility.Collapsed;

        }

        void InvalidateTextQ()
        {
            foreach (TextBlock textblock in searchCpanel.Children)
            {
                textblock.Foreground = new SolidColorBrush(Colors.LightGray);
            }
        }

        void drawFarOut_Completed(object sender, EventArgs e)
        {
            // MessageBox.Show("executed back");
            listBox.ItemsSource = (System.Collections.IEnumerable)Contexts.Pop();
            InvalidateTextQ();
            drawFarIn.Begin();
            throttleSpeed.Visibility = System.Windows.Visibility.Visible;
            if (EquivalantTier != 1)
                toggleShowAll.IsEnabled = true;
            //  progressbar.Visibility = System.Windows.Visibility.Collapsed;

        }

        void refreshList_Completed(object sender, EventArgs e)
        {
            if (toggleShowAll.Content.ToString() == "showing context")
            {
                listBox.ItemsSource = now;
            }
            else
            {
                if (EquivalantTier == 1)
                {
                    throw new ApplicationException("BUGCHECK");
                }
                if (EquivalantTier == 2)
                {
                    listBox.ItemsSource = DataRepository.KnowledgePoints;
                }
                if (EquivalantTier == 3)
                {
                    listBox.ItemsSource = DataRepository.Questions;
                }
            }
            InvalidateTextQ();
            refreshListShow.Begin();
            //progressbar.Visibility = System.Windows.Visibility.Collapsed;
        }

        void showSearch_Completed(object sender, EventArgs e)
        {
            if (showSearch.GetCurrentState() == ClockState.Active)
            {
                return;
            }
            textBox.Text = "";
        }
        Storyboard shrink;
        Storyboard expand;
        Storyboard fadeIn;
        Storyboard fadeOut;
        Storyboard showSearch;
        Storyboard refreshListFade;
        Storyboard refreshListShow;
        Storyboard drawFarIn;
        Storyboard drawNearIn;
        Storyboard drawFarOut;
        Storyboard drawNearOut;
        Storyboard fastFadeLeft;
        Storyboard flashStackPanel;
        Storyboard turnWhite;
        Storyboard turnRed;
        bool expanded;
        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            if (!expanded)
            {
                expanded = true;
                expandDetail();
            }
            else
            {
                expanded = false;
                hideDetail();
            }
        }

        private void hideDetail()
        {
            (shrink.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[0].Value = listBox.ActualHeight - 10;
            shrink.Begin();
        }

        private void expandDetail()
        {
            (expand.Children[0] as DoubleAnimationUsingKeyFrames).KeyFrames[1].Value = listBox.ActualHeight - 10;
            expand.Begin();
        }
        TabItem lastItem;
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            try
            {
                var current = tabCtrl.SelectedItem as TabItem;
                if (current == lastItem)
                    return;
                fadeIn.Begin((current.Content as Grid));
                if (current == dangerZone)
                {
                    turnRed.Begin();
                }
                else
                {
                    turnWhite.Begin();
                }
                if (current == settingsItem)
                {
                    flashStackPanel.Begin();
                }

                lastItem = current;
            }
            catch
            {
            }
        }

        private void TabItem_KeyUp(object sender, KeyEventArgs e)
        {
            if (tabCtrl.SelectedItem != datahitem)
            {
                return;
            }
            if (e.Key == Key.Enter)
            {
                if (listBox.ItemsSource != null)
                {
                    if (textBox.Text.Length == 0)
                    {
                        listBox.ItemsSource = Contexts.Peek() as System.Collections.IEnumerable;
                    }
                    else if (listBox.Items.Count != 0)
                    {
                        listBox.ItemsSource = listBox.ItemsSource.Cast<ISearchable>().Where<ISearchable>(o =>
                        {
                            return o.SearchTag.ToUpperInvariant().Contains(textBox.Text);
                        });
                    }
                }
                InvalidateTextQ();
                return;
            }
            if (e.Key.ToString().Length > 2 && e.Key != Key.Back)
            {
                return;
            }
            if (e.Key != Key.Back)
            {
                var added = e.Key.ToString();
                if (added.StartsWith("D") && added.Length == 2)
                {
                    added = added.Substring(1, 1);
                }
                textBox.Text += added;
            }
            else if (textBox.Text.Length >= 1)
            {
                textBox.Text = textBox.Text.Substring(0, textBox.Text.Length - 1);
            }
            showSearch.Begin();

        }

        private void searchQChanged(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            // TODO: Add event handler implementation here.

            if (listBox.ItemsSource != null)
            {
                if (sender == title)
                {
                    listBox.ItemsSource = (listBox.ItemsSource as IEnumerable<ISearchable>).OrderBy<ISearchable, string>(o =>
                           {
                               return o.Title;
                           });
                }
                if (sender == summary)
                {
                    listBox.ItemsSource = (listBox.ItemsSource as IEnumerable<ISearchable>).OrderBy<ISearchable, string>(o =>
                    {
                        return o.Summary;
                    });
                }
                if (sender == errorrate)
                {
                    listBox.ItemsSource = (listBox.ItemsSource as IEnumerable<ISearchable>).OrderBy<ISearchable, double>(o =>
                    {
                        return o.NumericSummary;
                    });
                }
                if (sender == date)
                {
                    listBox.ItemsSource = (listBox.ItemsSource as IEnumerable<ISearchable>).OrderBy<ISearchable, DateTime>(o =>
                    {
                        return o.Date;
                    });
                }
                InvalidateTextQ();
                (sender as TextBlock).Foreground = new SolidColorBrush(Colors.Black);
            }
        }

        private void StackPanel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            hideDetail();
            detailTextBlock.Text = (sender as StackPanel).DataContext.ToString();
            errorRate.Text = DataRepository.CalculateErrorRate((sender as StackPanel).DataContext).ToString() + "%";
            expandDetail();
        }
        Hyperlink clicked;
        private void Hyperlink_Click_1(object sender, RoutedEventArgs e)
        {
            if (Contexts.Count == 2)
            {
                return;
            }
            if (equivalantTier == 3)
            {
                return;
            }
            EquivalantTier++;
            //progressbar.Visibility = System.Windows.Visibility.Visible;
            this.Contexts.Push(listBox.ItemsSource);
            clicked = sender as Hyperlink;
            throttleSpeed.Visibility = Visibility.Collapsed;
            toggleShowAll.Content = "showing context";
            toggleShowAll.IsEnabled = false;
            toggleShowAll.IsChecked = false;
            //MessageBox.Show("preparing to launch");
            drawNearOut.Begin();

        }

        private void Path_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (Contexts.Count() > 0)
            {
                EquivalantTier--;
                //progressbar.Visibility = System.Windows.Visibility.Visible; 
                toggleShowAll.IsEnabled = false;
                throttleSpeed.Visibility = Visibility.Collapsed;
                toggleShowAll.IsChecked = false;
                toggleShowAll.Content = "showing context";
                //   MessageBox.Show("preparing to launch");
                drawFarOut.Begin();

            }

        }
        System.Collections.IEnumerable now;
        private void toggleShowAll_Click(object sender, RoutedEventArgs e)
        {
            if (toggleShowAll.Content.ToString() == "showing all")
            {
                toggleShowAll.Content = "showing context";
            }
            else
            {
                now = listBox.ItemsSource;
                toggleShowAll.Content = "showing all";
            }
            //progressbar.Visibility = System.Windows.Visibility.Visible;
            refreshListFade.Begin();
        }

        private void Run_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink hl = sender as Hyperlink;
            System.Diagnostics.Process.Start(hl.NavigateUri.ToString());
        }
        object lastSetting = null;
        private void TextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            if (sender == lastSetting)
            {
                return;
            }
            foreach (TextBlock tb in settingsPanel.Children)
            {
                tb.Foreground = new SolidColorBrush(Colors.Gray);
            }
            lastSetting = sender;
            (sender as TextBlock).Foreground = new SolidColorBrush(Colors.Black);
            int idx = settingsPanel.Children.IndexOf(sender as UIElement);
            tabControl.SelectedIndex = idx;
            fastFadeLeft.Begin();
            ((indicator.RenderTransform as System.Windows.Media.TransformGroup).Children[3] as TranslateTransform).Y = 21.28 * idx;
        }
        public static SolidColorBrush[] colors;
        static int colorenumerator;
        static Result()
        {
            Initialize();
        }
        public static void Initialize()
        {
            PropertyInfo[] pi = typeof(Colors).GetProperties();
            colors = new SolidColorBrush[pi.Count()];
            for (int i = 0; i < pi.Count(); i++)
            {
                colors[i] = new SolidColorBrush((Color)pi[i].GetValue(null, null));
            }
        }
        private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            var rect = sender as Rectangle;
            rect.Fill = colors[colorenumerator];
            if (sender == Fine)
            {
                Settings.Default.Fine = colorenumerator;
            }
            if (sender == Moderate)
            {
                Settings.Default.Moderate = colorenumerator;
            }
            if (sender == Severe)
            {
                Settings.Default.Severe = colorenumerator;
            }
            colorenumerator++;
            if (colorenumerator == colors.Count())
            {
                colorenumerator = 0;
            }
        }

        private void highlightGauge_TextChanged(object sender, TextChangedEventArgs e)
        {
            int data;
            if (int.TryParse(highlightGauge.Text, out data))
            {
                highlightGauge.Background = new SolidColorBrush(Colors.White);
                highlightGauge.Foreground = new SolidColorBrush(Colors.Black);
            }
            else
            {
                highlightGauge.Background = new SolidColorBrush(Colors.Red);
                highlightGauge.Foreground = new SolidColorBrush(Colors.White);
            }
        }

        private void Apply_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Save();
            Apply.Visibility = System.Windows.Visibility.Collapsed;
            Cancel.Visibility = System.Windows.Visibility.Collapsed;
            changeApplyNextTime.Visibility = System.Windows.Visibility.Visible;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Reload();
            RefreshSettingPanel();
            Apply.Visibility = Cancel.Visibility = System.Windows.Visibility.Collapsed;
            changeApplyNextTime.Visibility = System.Windows.Visibility.Collapsed;
        }
        int lvl;
        static string[] GraphicsSummary = { "maximizes performance", "balance effects and performance", "maximize transition effects" };
        private void slider_DragDelta(object sender, System.Windows.Controls.Primitives.DragDeltaEventArgs e)
        {
            if (e.HorizontalChange < -50)
            {
                lvl--;
                if (lvl < 0)
                    lvl = 0;
            }
            else if (e.HorizontalChange > 50)
            {
                lvl++;
                if (lvl > 2)
                    lvl = 2;
            }
            slider.RenderTransform = new TranslateTransform(lvl * 100, 0);
            pastRect.Width = lvl * 100;
            Settings.Default.GraphicsLevel = lvl;
            effectSummary.Text = GraphicsSummary[lvl];
        }
        void update_Bug_Check(string s, bool redo = false)
        {
            this.Dispatcher.Invoke(new Action(() =>
                {
                    if (redo)
                    {
                        ftptrace.Text = "";
                    }
                    ftptrace.Text += s + "\n";
                }));
        }
        private void check_update_Click(object sender, RoutedEventArgs e)
        {
            ftptrace.Text = "";
            check_update.IsEnabled = false;
            update_indicator.Visibility = System.Windows.Visibility.Visible;
            System.Threading.ThreadPool.QueueUserWorkItem(o =>
                {
                    try
                    {
                        OfflineTask.AddOfflineTask(OfflineTask.OfflineTaskType.Update);
                        update_Bug_Check("preparing to connect soft.nankai.edu.cn...");
                        UpdateTask ut = new UpdateTask("0.9", "upload", "upload");
                        if (ut.NewVersionDetected())
                        {
                            System.Threading.Thread.Sleep(2000);
                            update_Bug_Check("new version has been detected.");
                            update_Bug_Check("new version is " + ut.NewVersion);
                            update_Bug_Check("restart the application to run Update utility.");
                        }
                        else
                        {
                            update_Bug_Check("this application is up-to-date.");
                        }
                    }
                    catch
                    {
                        update_Bug_Check("a problem has occured during update.", true);
                    }
                    this.Dispatcher.Invoke(new Action(() =>
                        {
                            check_update.IsEnabled = true;
                            update_indicator.Visibility = System.Windows.Visibility.Collapsed;
                        }));
                });
        }

        private void Hyperlink_Click_2(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start((sender as Hyperlink).NavigateUri.ToString());
        }

        private void dropQuestions_Click(object sender, RoutedEventArgs e)
        {
            if (!LocalDBManipulation.LocalDBManipulator.DeleteAllQuestions())
            {
                MessageBox.Show("!");
            }
        }

        private void dropKnowledgePoints_Click(object sender, RoutedEventArgs e)
        {
            if (!LocalDBManipulation.LocalDBManipulator.DeleteAllKnowledgePoint())
            {
                MessageBox.Show("!");
            }
        }

        private void dropPapers_Click(object sender, RoutedEventArgs e)
        {
            if (!LocalDBManipulation.LocalDBManipulator.DeleteAllPaper())
            {
                MessageBox.Show("!");
            }
        }

        private void resetSettings_Click(object sender, RoutedEventArgs e)
        {
            Settings.Default.Reset();
            RefreshSettingPanel();
        }

        private void help_me_decide_visual_Click(object sender, RoutedEventArgs e)
        {
            var check = help_me_decide_visual.IsChecked.Value;
            if (check)
            {
                GenerateWINSATSummary();
            }
            else
            {
                experienceIndexRoot.Visibility = System.Windows.Visibility.Collapsed;
                performanceRetrievingIndicator.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

    }
    class ListBoxQuestionDataTemplateSelector : DataTemplateSelector
    {
        public override DataTemplate SelectTemplate(object item, DependencyObject container)
        {
            FrameworkElement element = container as FrameworkElement;

            if (element != null && item != null)
            {
                double value = (item as ISearchable).NumericSummary;
                if (value >= Settings.Default.PercentageHighlight)
                {
                    return element.FindResource("GrayBackground") as DataTemplate;
                }
                else
                {
                    return element.FindResource("WhiteBackground") as DataTemplate;
                }
            }

            return null;
        }
    }
    class ColorConverter : IValueConverter
    {
        public object Convert(object o, Type t, object o1, System.Globalization.CultureInfo gi)
        {
            double d = (int)o;
            if (d <= 33)
            {
                return Result.colors[Settings.Default.Fine];
            }
            else if (d <= 66)
            {
                return Result.colors[Settings.Default.Moderate];
            }
            else
            {
                return Result.colors[Settings.Default.Severe];
            }
        }
        public object ConvertBack(object o, Type t, object o1, System.Globalization.CultureInfo gi)
        {
            return null;
        }
    }
    class StringConverter : IValueConverter
    {
        public object Convert(object o, Type t, object o1, System.Globalization.CultureInfo gi)
        {
            string d = o.ToString();
            return d.Replace("\n", " ");
        }
        public object ConvertBack(object o, Type t, object o1, System.Globalization.CultureInfo gi)
        {
            return null;
        }
    }

    class ReverseEnabledConverter : IValueConverter
    {
        public object Convert(object o, Type t, object o1, System.Globalization.CultureInfo gi)
        {
            return !((bool?)o).Value;
        }
        public object ConvertBack(object o, Type t, object o1, System.Globalization.CultureInfo gi)
        {
            return null;
        }
    }
}